<?php
function strtotitle($str,$encoding="UTF-8"){
	
	$enc = mb_detect_encoding($str);
	if ($enc != $encoding) {
		$str = mb_convert_encoding($str,$encoding);
	}
	$first = mb_substr($str,0,1,$encoding);
	
	$len = mb_strlen($str,$encoding);
	$rest = mb_substr($str,1,$len-1,$encoding);
	
	$ret = mb_strtoupper($first,$encoding).mb_strtolower($rest,$encoding);
	
	return $ret;
}
function getFileExtension($filename){
	$last = strrpos($filename,".");
	return substr($filename,$last+1);
}
function getFromTemplate($file){
	if($f = file("templates/".$file)){
		return implode("",$f);
	}else{
		return false;
	}
}
function getFromCfg(){
	$fname = "cfg/config.cfg";
	if($f = file($fname)){
		foreach ($f as $k=>$v){
			if(!preg_match('/^#/',$v)){
				$tmp = explode("=",$v);
				$ret[$tmp[0]] = $tmp[1];
			}
		}
		return $ret;
	}else{
		die("Greška pri otvaranju konfiguracionog fajla!");
	}
}

function prepForSQL($str,$quote="'"){
	$str = str_replace($quote,"\\".$quote,$str);
	return $str;
}

function jsAlert($msg){
	echo '<script>alert("'.$msg.'")</script>';
}
function utf8RawUrlDecode ($source) {
	$decodedStr = '';
	$pos = 0;
	$len = strlen ($source);
	while ($pos < $len) {
			$charAt = substr ($source, $pos, 1);
			if ($charAt == '%') {
				$pos++;
				$charAt = substr ($source, $pos, 1);
				if ($charAt == 'u') {
					// we got a unicode character
					$pos++;
					$unicodeHexVal = substr ($source, $pos, 4);
					$unicode = hexdec ($unicodeHexVal);
					$entity = "&#". $unicode . ';';
					$decodedStr .= utf8_encode ($entity);
					$pos += 4;
				}else {
					
					if(preg_match('/^\d+$/',substr ($source, $pos, 2))){// we have an escaped ascii character
						$hexVal = substr ($source, $pos, 2);
						$decodedStr .= chr (hexdec ($hexVal));
						$pos += 2;
					}else{
						$decodedStr .= "%".$charAt;
						$pos++;
					}
				}
			}else {
				$decodedStr .= $charAt;
				$pos++;
			}
	}
	return $decodedStr;
}
function utf8RawChrDecode($str){
	$mask = array(
		262 => "Ć",
		263 => "ć",
		268 => "Č",
		269 => "č",
		352 => "Š",
		353 => "š",
		381 => "Ž",
		382 => "ž",
		272 => "Đ",
		273 => "đ"
	);
	foreach ($mask as $k=>$v){
		$str = str_replace("&#$k;",$v,$str);
	}
	return $str;
}

function utf82cp1250($str){
	$mask = array(
		"Č" => chr(196).chr(140),
		"č" => chr(196).chr(141),
		"Ć" => chr(196).chr(134),
		"ć" => chr(196).chr(135),
		"Š" => chr(197).chr(160),
		"š" => chr(197).chr(161),
		"Đ" => chr(196).chr(144),
		"đ" => chr(196).chr(145),
		"Ž" => chr(197).chr(189),
		"ž" => chr(197).chr(190)
	);
	foreach ($mask as $k=>$v){
		$str = str_replace($k,$v,$str);
	}
	return $str;
}

function unescape($str){
	$tmp = preg_split('/(%u\d{4})/',$str,-1,PREG_SPLIT_DELIM_CAPTURE);
	$return = "";
	
	foreach ($tmp as $line){
		if(preg_match('/^%u/',$line)){
			$hex = intval(substr($line,2,4));
			$dec = hexdec($hex);
			$chr = "&#$dec;";
			$line = utf8_encode($chr);
		}
		$return .= $line;
	}
	
	return $return;
}
function debug($input,$style="width: 400px; height:300px"){
	if(is_array($input) or is_object($input)){
	?>
	<textarea style="<?php echo $style ?>">
	<?php print_r($input); ?>
	</textarea>
	<?php
	}else{
		echo "<p>$input</p>";
	}
}
function array_chunk_vertical($data, $columns) {
   $n = count($data) ;
   $per_column = floor($n / $columns) ;
   $rest = $n % $columns ;

   // The map
   $per_columns = array( ) ;
   for ( $i = 0 ; $i < $columns ; $i++ ) {
       $per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ;
   }

   $tabular = array( ) ;
   foreach ( $per_columns as $rows ) {
       for ( $i = 0 ; $i < $rows ; $i++ ) {
           $tabular[$i][ ] = array_shift($data) ;
       }
   }

   return $tabular ;
}
function currency($val){
	$val = number_format($val,2,",",".");
	return $val;
}

function removeZeroVals(){
	$args = func_get_args();
	$ids = $args[0];
	$args = array_splice($args,1);
	foreach ($ids as $k=>$v){
		if($v<1){
			unset($ids[$k]);
			foreach ($args as $m=>$n){
				unset($args[$m][$k]);
			}
		}
	}
	$ret = array(array_values($ids));
	foreach ($args as $k=>$v){
		$args[$k] = array_values($v);
	}
	$ret = array_merge($ret,$args);
	//echo "<p>"; print_r($ret); echo "</p>";
	return $ret;
}

function array_removeEmptyItems(&$arr){
	foreach ($arr as $k=>$v){
		if(strlen(trim($v))==0){
			unset($arr[$k]);
		}
	}
}
function print_rarray($arr){
	echo "<pre>";
	print_r($arr);
	echo "</pre>";
}
function getFromInput($name,$trim=false){
	$ret = isset($_GET[$name])?$_GET[$name]:(isset($_POST[$name])?$_POST[$name]:"");
	$ret = $trim?trim($ret):$ret;
	return $ret;
}
function readValFromInput($name,$trim=false){
	$val = getFromInput($name,$trim);
	if(strlen($val)){
		$val = utf8RawUrlDecode($val);
		$val = utf8RawChrDecode($val);
	}
	return $val;
}
function prepareNasaSlovaFOX($str){
	$ret = "";
	for($i=0; $i<strlen($str)-1; $i++){
		$chr = substr($str,$i,1);
		$int = ord($chr);
		switch ($int){
			case 230:
				$chr = "Ä‡";
				break;
		}
		$ret .= $chr;
	}
	return $ret;
}

function nasaslova($x){
	$mask = array(
		"s" => "š",
		"S" => "Š",
		"dj" => "đ",
		"DJ" => "Đ",
		"z" => "ž",
		"Z" => "Ž",
		"c" => "ć",
		"C" => "Ć",
		"c" => "č",
		"C" => "Č"
	);
	
	foreach ($mask as $k=>$v){
		$x = str_replace($v,$k,$x);
	}
	return $x;
}
function stripLatins($str){
	$mask = array(
		"č"	=>	"c",
		"Č"	=>	"C",
		"ć"	=>	"c",
		"Ć"	=>	"C",
		"š"	=>	"s",
		"Š"	=>	"S",
		"đ"	=>	"dj",
		"Đ"	=>	"DJ",
		"ž"	=>	"z",
		"Ž"	=>	"Z"
	);
	foreach ($mask as $k=>$v){
		$str = str_replace($k,$v,$str);
	}
	return $str;
}
function utf2yuscii($str,$reverse=false){
	$maska = array(
		"č" => "~",
		"Č" => "^",
		"ć" => "}",
		"Ć" => "]",
		"š" => "{",
		"Š" => "[",
		"đ" => "|",
		"Đ" => "\\",
		"ž" => "`",
		"Ž" => "@",
	);
	$ret = $str;
	foreach ($maska as $k=>$v){
		if($reverse==false){
			$ret = str_replace($k,$v,$ret);
		}else{
			$ret = str_replace($v,$k,$ret);
		}
	}
	return $ret;
}

function date2int($date,$delimiter=".",$order=array("day"=>0,"month"=>1,"year"=>2)){
	$tmp = explode($delimiter,$date,3);
	if($tmp[$order["year"]]<1970 || $tmp[$order["year"]]>2037){
		$time=0;
	}else {
		//$time = mktime(0,0,0,$tmp[$order["month"]],$tmp[$order["day"]],$tmp[$order["year"]]);
		$time = makeUnixTime(0,0,0,$tmp[$order["month"]],$tmp[$order["day"]],$tmp[$order["year"]]);
	}
	return $time;
}
function int2date($timestamp,$format="d.m.Y"){
	$timestamp=(int)$timestamp;
	if ($timestamp>0) {
		return date($format,$timestamp);
	}else{
		return "";
	}
}

function datetime2str($date,$time=false){
	
	if(
		preg_match('/\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})|\d{4}-\d{2}-\d{2}/',$date) && !preg_match('/^0000-00-00 00:00:00$/',$date)
		){
		$tmp = preg_split('/(\d{4})-(\d{2})-(\d{2})( \d{2}:\d{2}:\d{2})*/i',$date,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
		$tmp[2] = ($tmp[2]<10 && !preg_match('/^0/',$tmp[2]))?"0".$tmp[2]:$tmp[2];
		$tmp[1] = ($tmp[1]<10 && !preg_match('/^0/',$tmp[1]))?"0".$tmp[1]:$tmp[1];
		$tmp[0] = ($tmp[0]<10 && !preg_match('/^0/',$tmp[0]))?"0".$tmp[0]:$tmp[0];
		
		$ret = $tmp[2].".".$tmp[1].".".$tmp[0];
		
		if($time){
			print_rarray($tmp);
			$ret .=" ".$tmp[3];
		}
	}else{
		$ret = "";
	}
	return $ret;
}
function str2datetime($str,$time=1){
	$tmp = explode(" ",$str);
	$tmp = explode(".",$tmp[0]); $tmp1 = $tmp[1];
	
	$datetime = $tmp[2]."-".$tmp[1]."-".$tmp[0];
	if($time){
		$datetime .= " $tmp1";
	}
	return $datetime;
}

function getSimpleTable($columns,$rows,$onclick=array(),$tableAttrs=array(),$indexColumn=true){
	//print_rarray($columns);
	$out = "\r\n".'<table';
	foreach ($tableAttrs as $name=>$val){
		$out .= " $name=\"$val\"";
	}
	$out .= '>';
	$out .= "\r\n\t<tr class=\"head\">";
	if($indexColumn===true){
		$ou .= "\r\n\t\t<td>#</td>";
	}
	foreach ($columns as $k=>$v){
		$out .= "\r\n\t\t<td>$v</td>";
	}
	$out .= "\r\n\t</tr>";
	foreach ($rows[0] as $k=>$v){
		$out .= "\r\n\t<tr onclick=\"".$onclick[$k]."\">";
		if($indexColumn===true){
			$out .= "\r\n\t\t<td>".($k+1).".</td>";
		}
		foreach ($columns as $m=>$n){
			$out .= "\r\n\t\t<td>".$rows[$m][$k]."</td>";
		}
		$out .= "\r\n\t</tr>";
	}
	
	$out .= "\r\n</table>";
	
	return $out;
}

function makeUnixTime($hour,$min,$sec,$mon,$day,$year){
	$hour = intval($hour);
	$min = intval($min);
	$sec = intval($sec);
	$mon = intval($mon);
	$day = intval($day);
	$year = intval($year);
	return mktime($hour,$min,$sec,$mon,$day,$year);
}

function encoding_latin($str,$reverse=false){
	$mask = array(
		"č" => chr(195).chr(168),
		"Č" => chr(195).chr(136),
		"ć" => chr(195).chr(166),
		"Ć" => chr(195).chr(134),
		"š" => chr(194).chr(154),
		"Š" => chr(194).chr(138),
		"đ" => chr(195).chr(176),
		"Đ" => chr(195).chr(144),
		"ž" => chr(194).chr(158),
		"Ž" => chr(194).chr(142)
	);
	
	foreach ($mask as $k=>$v){
		if ($reverse) {
			$str = str_replace($v,$k,$str);
		}else{
			$str = str_replace($k,$v,$str);
		}
	}
	return $str;
}

function ipPhoneLink($phone){
	
	$ip = $_SERVER['REMOTE_ADDR'];
	$local = substr($ip,strrpos($ip,".")+1);
	if ($local>199) {
		$local = $local-100;
	}
	$phone = preg_replace('/[^\d]/',"",$phone);
	return '<a title="Pozovite '.$phone.'" href="http://192.168.5.2/gw/call.php?l='.$local.'r='.$phone.'">'.$phone.'</a>';
}

function strip_number_format($v){
	$v = str_replace(".","",$v);
	$v = str_replace(",",".",$v);
	return $v;
}
function strip_tag_attributes($html){
	$rgx = '/(<[a-zA-Z1..9]+)\s*([a-z]+=".*?")*\/*(>)/i';
	$split = preg_split($rgx,$html,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
	$intag=false;
	foreach ($split as $k=>$v){
		
		if (preg_match('/^</',$v)) {
			$intag=true;
		}else if (preg_match('/^>/',$v)) {
			$intag=false;
		}else if ($intag) {
			unset($split[$k]);
		}
	}
	
	return implode("",$split);
}

function PageFilter($page,$length){
	$ret = array();
	for ($i=0; $i<$length; $i++){
		$ret["page"][$i] = $i+1;
		$ret["current"][$i] = ($i+1)==$page?"current":"";
	}
	return $ret;
}

function sec2time($sec){
	$sec = intval($sec);
	if ($sec>0) {
		$hours = bcdiv($sec,60*60,0); $hours = $hours<10?"0$hours":$hours;
		$mins = bcdiv($sec%(60*60),60,0); $mins = $mins<10?"0$mins":$mins;
		return "$hours:$mins";
	}else{
		return "0";
	}
	
}

function is_valid_date($date){
	$rgx = '/^\d{1,2}\.\d{1,2}\.\d{2,4}$/';
	if (preg_match($rgx,$date)) {
		return true;
	}else{
		return false;
	}
}

function LoadCSV($src,$header=true){
	$file = file($src);
	if ($header) {
		$file = array_slice($file,1);
	}
	foreach ($file as $line){
		$items = explode("\t",$line);
		$items = array_map("trim",$items);//print_rarray($items);
		$ret[] = $items;
	}
	
	return $ret;
}
?>